import wheels.pi.aio as aio

from wheels.pi.aio.AsyncOperation import RecvOperation, SendOperation
from wheels.pi.aio.Proactor import EventHandler


class AsyncStream(object):

    class _ProactiveHandler(EventHandler):

        def __init__(self, handler, act):
            self._handler = handler
            self._act = act

        def handle_recv(self, buf):
            self._handler.handle_event("recv", buf, self._act)

        def handle_send(self, cnt):
            self._handler.handle_event("send", cnt, self._act)


    def __init__(self, handle, proactor, handler):
        self._handle = handle
        self._proactor = proactor
        self._handler = handler


    def recv(self, cnt, act = None):
        op = RecvOperation(self._handler, cnt)
        proactive = AsyncStream._ProactiveHandler(self._handler, act)
        aio.register(op, self._proactor, proactive)


    def send(self, buf, act = None):
        op = SendOperation(self._handler, buf)
        proactive = AsyncStream._ProactiveHandler(self._handler, act)
        aio.register(op, self._proactor, proactive)
